// 状态
import {
  getBaseCategoryList,
  getGoodsList,
  getRankList,
  getLikeList,
  getFloorList,
  postSearchList,
  getGoodsDetail,
} from '@/api/product'
//定义状态数据state
const state = {
  // 三级分类数据
  categoryList: [],
  // 商品排行
  rankList: [],
  // 货物排行
  goodsList: [],
  //猜你喜欢
  likeList: [],
  //猜你喜欢的总页数
  likePageTotal: 1,
  //楼层
  floorList: [],
  //搜索商品
  searchResult: {
    pageNo: 1,
    pageSize: 5,
    Total: 1,
  },
  GoodsDetail: {},
}

//定义mutations给数据状态
const mutations = {
  CHANGE_ACTIVEINDEX_BYID(state, payload) {
    // payload-->{id:条件,activeIndex:修改的值}
    const info = state.floorList.find((v) => v.id === payload.id)
    info.activeIndex = payload.activeIndex
  },

  // 更新三级分类数据
  UP_CATEGORY_LIST(state, payload) {
    state.categoryList = payload
  },
  //更新rank
  UP_RANKLIST(state, payload) {
    state.rankList = payload
  },
  //更新货物排行
  UP_GOODSLIST(state, payload) {
    state.goodsList = payload
  },
  //更新热爱排行
  UP_LIKELIST_AND_PAGESUM(state, payload) {
    state.likeList = payload.likeList
    state.likePageTotal = payload.pageTotal
  },
  //更新楼层
  UP_FLOORLIST(state, payload) {
    state.floorList = payload
  },
  //更新搜索结果
  UP_SEARCH_RESULT(state, payload) {
    state.searchResult = payload
  },
  //更新商品详情
  UP_GOODS_DETAIL(state, payload) {
    state.GoodsDetail = payload
  },
}

// action:异步行为
const actions = {
  // 获取三级数据分类 解构赋值
  async getBaseCategoryListAsync({ commit, state }, limit = 15) {
    //若categoryList.length > 0直接返回
    if (state.categoryList.length > 0) return
    const res = await getBaseCategoryList()
    commit('UP_CATEGORY_LIST', res.data.slice(0, limit))
  },
  //获取商品排行
  async getRankListAsync({ commit }) {
    const res = await getRankList()
    commit('UP_RANKLIST', res.rankList)
  },
  // 获取货物排行
  async getGoodsListAsync({ commit }, type = 1) {
    const res = await getGoodsList(type)
    commit('UP_GOODSLIST', res.goodsList)
  },
  //获取猜你喜欢
  async getLikeListAsync({ commit }, { pageNum, pageSize = 6 }) {
    const res = await getLikeList(pageNum, pageSize)
    commit('UP_LIKELIST_AND_PAGESUM', res)
  },
  //获取楼层
  async getFloorListAsync({ commit }) {
    const res = await getFloorList()
    commit('UP_FLOORLIST', res.floorList)
  },
  // 获取搜索
  async postSearchListAsync({ commit }, body) {
    const res = await postSearchList(body)
    commit('UP_SEARCH_RESULT', res.data)
  },
  //获取商品详情
  async getGoodsDetailAsync({ commit }, id) {
    const res = await getGoodsDetail(id)
    commit('UP_GOODS_DETAIL', res.data)
  },
}
export default {
  namespaced: true,
  state,
  actions,
  mutations,
}
